import urllib.request
import urllib.parse
import execjs
import json


class WYYMusic(object):
    def __init__(self):
        self.header = {
            "accept": "*/*",
            "accept-language": "zh-CN,zh;q=0.9",
            "content-type": "application/x-www-form-urlencoded",
            "cookie": "_iuqxldmzr_=32; _ntes_nnid=fd0e158e7adb1b3e53c310ebeb58d77d,1564830032177; _ntes_nuid=fd0e158e7adb1b3e53c310ebeb58d77d; playerid=69204524; JSESSIONID-WYYY=%5Ce%2BJkuPpde91iGjV30dXl56CPigWXpOwpg21A%5CwOCPNzYkRcGtw%2Br20UoKlQDjQbG2%2BcK%2FGpWHRn34WwzNWUEfjpgtbaifGaNryyEqoZOFW6EeWrm2nj41XDldbIeWshK3oKnfmQjT7Vkth4PUIpPjrsdAGqoAG5l4I8453Mw9Fdsvb0%3A1564837522441",
            "origin": "https://music.163.com",
            "referer": "https://music.163.com/",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36",
        }
        self.data = {
            "params": "",
            "encSecKey": ""
        }
        self.id = ""
        self.url = ""

        self.d = ""
        self.e = "010001"
        self.f = "00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7"
        self.g = "0CoJUm6Qyw8W8jud"

        with open('wangyiyun.js', 'r', encoding='utf-8') as file:
            self.js_fun = execjs.compile(file.read())

    def update_id(self, song_id):
        self.id = song_id
        self.url = f'https://music.163.com/weapi/v1/resource/comments/R_SO_4_{self.id}?csrf_token='

    def cal_params(self):
        params = self.js_fun.call('d', self.d, self.e, self.f, self.g)
        self.data['params'] = params['encText']
        self.data['encSecKey'] = params['encSecKey']

    def get_comments(self, page_number=0):
        self.d = f'{{"rid":"R_SO_4_{self.id}","offset":"{20*page_number}","total":"true","limit":"20","csrf_token":""}}'
        self.cal_params()
        req = urllib.request.Request(url=self.url, data=urllib.parse.urlencode(self.data).encode('utf-8'), headers=self.header)
        response = json.loads(urllib.request.urlopen(req).read().decode('utf-8'))
        for item in response["comments"]:
            print(item)


if __name__ == '__main__':
    wy = WYYMusic()
    wy.update_id('444267215')
    wy.get_comments()
